import React, { FC, DragEvent, useRef, useEffect, useState, RefObject } from 'react';
import { Upload } from 'choerodon-ui/pro';
import styles from './index.less';

export interface UploadDragProps {}

function useDragDrop<T extends HTMLElement, F extends Upload>(): {containerRef: RefObject<T>, uploadRef: RefObject<F>, status: 'over'|'end'|'leave'} {
  const containerRef = useRef<T | null>(null);
  const uploadRef = useRef<F | null>(null);
  const [status, setStatus] = useState<'over'|'end'|'leave'>('end');
  useEffect(() => {
    function onDragOver(e: DragEvent<any>) {
      e.preventDefault();
      setStatus('over');
    }
    function onDrop(e: DragEvent<T>) {
      e.preventDefault();
      if (uploadRef.current) {
        uploadRef.current.handleChange({target: {files: e.dataTransfer.files}});
      }
      setStatus('end');
    }
    function onDragLeave() {
      setStatus('leave');
    }
    const containerEl = containerRef.current;
    if (containerEl) {
      containerEl.addEventListener<any>('dragover', onDragOver);
      containerEl.addEventListener<any>('drop', onDrop);
      containerEl.addEventListener<any>('dragleave', onDragLeave);
    }
    return () => {
      if (containerEl) {
        containerEl.removeEventListener<any>('dragover', onDragOver);
        containerEl.removeEventListener<any>('drop', onDrop);
      }
    };
  }, []);
  return {containerRef, uploadRef, status};
}

const UploadDrag: FC<UploadDragProps> = () => {
  const uploadProps = {
    headers: {
      'Access-Control-Allow-Origin': '*',
    },
    action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
    multiple: true,
    accept: ['.deb', '.txt', '.pdf', 'image/*'],
    uploadImmediately: false,
    showUploadList: true,
  };
  const {containerRef, uploadRef, status} = useDragDrop<HTMLDivElement, Upload>();
  const containerClassNames = [styles['upload-drag'], styles[`upload-drag-${status}`]];
  return (
    <div
      ref={containerRef}
      className={containerClassNames.join(' ')}
    >
      <Upload ref={uploadRef} {...uploadProps} />
      <div className={styles.desc}>
        {status === 'over' ? '释放鼠标以上传' : '拖拽到此处以上传'}
      </div>
    </div>
  );
};

export default UploadDrag;
